/*
 * @Author: Penk
 * @LastEditors: Penk
 * @LastEditTime: 2021-11-04 00:58:49
 * @FilePath: \多多插件\views\global_kyy\global\index.js
 */
window.addEventListener("load", async () => {
  // $$ = jQuery.noConflict();
  // 右上角按钮框
  initBox();

  if (localStorageGetItem("kyy")) {
    kyy = localStorageGetItem("kyy");
  } else {
    localStorageSetItem("kyy", kyy);
  }

  let date = new Date();
  let dateStr = "" + date.getFullYear();
  dateStr += "" + (date.getMonth() + 1);
  dateStr += "" + date.getDate();

  // 判断客优云存储的时间，主要是汇率变化
  if (kyy.dateStr != dateStr) {
    kyy.tbRate = null;
  }

  // 获取存储的汇率
  $("#tbRate").val(kyy.tbRate);
});

// 客优云弄个固定窗口存放按钮
async function initBox() {
  var kyyBox = document.createElement("div");
  kyyBox.setAttribute("class", "kyyBox");
  document.body.appendChild(kyyBox);

  $(".kyyBox").append(
    '<div class="kkyContent">' +
    '<button class="oneKeyBtn pddBtn" style="width:100%;">一键设置</button>' +
    "<br>" +
    '<select id="siteSelect">' +
    '<option value="台湾">台湾</option>' +
    '<option value="马来西亚">马来西亚</option>' +
    "</select>" +
    "<br>" +
    '<textarea rows="5" class="textarea">请替换拼多多一键打包的数据，采集页面才需要~~~</textarea>' +
    "<br>" +
    '<button class="getPddDataBtn pddBtn">读取拼多多数据</button>' +
    "<br>" +
    "------------辅助功能------------" +
    "<br>" +
    '<button class="testBtn pddBtn">test</button>' +
    "<br>" +
    '台币汇率：<input id="tbRate" class="tbRate">' +
    '<button class="initRateBtn pddBtn">初始化汇率</button>' +
    "<br>" +
    '打折数：<input id="discountInput" value="50" />' +
    '<button class="goodsBtn pddBtn">一键折扣</button>' +
    "<br>"
  );


  await wait(500);

  await initEvent();

  let temp = localStorageGetItem("kyy");
  if (temp.siteSelect) {
    $("#siteSelect").val(temp.siteSelect);
    $("#siteSelect").trigger("change");
  }
}

async function initEvent() {
  // 选择相对应的关键字
  $("#siteSelect").change((e) => {
    var val = $("#siteSelect").children("option:selected").val();

    kyy.siteSelect = val;
    localStorageSetItem("kyy", kyy);
  });

  $(".textarea").bind("input propertychange", () => {
    let data = JSON.parse($(".textarea").eq(0).val());
    kyyData.pddData.firstSku = data.firstSku;
    kyyData.pddData.originalPrice = data.originalPrice;

    kyyData.pddData.goodsTitle = data.goodsTitle;
    kyyData.pddData.skuKindNum = data.skuKindNum;
    kyyData.pddData.firstClassify = data.firstClassify;
    kyyData.pddData.filterSkuKind = data.filterSkuKind;
    kyyData.pddData.goods = data.goods;
    kyyData.pddData.priceType = data.priceType;
    kyyData.pddData.pddKeyWordDes = data.pddKeyWordDes;
    kyyData.pddData.goodsDetails = data.goodsDetails;
    kyyData.pddData.goodsDesc = data.goodsDesc;

    skuFilter.push(data.filterSkuKind);

    // 避免复制上上次的数据
    $copyText("请先拷贝拼多多一键打包数据，粘贴一次即可~~~");
  });

  // 读取拼多多数据
  $(".getPddDataBtn").click(async () => {
    if (isRunning) {
      console.log("isRunning...");
      return;
    }

    isRunning = true;

    await initPddData();

    isRunning = false;
  });

  // 监听台湾倍率
  $("#tbRate").change(() => {
    kyy.tbRate = $("#tbRate").val();
    let date = new Date();
    kyy.dateStr = "";
    kyy.dateStr = "" + date.getFullYear();
    /**测试加上毫秒 */
    // kyy.dateStr += "" + date.getMilliseconds();
    kyy.dateStr += "" + (date.getMonth() + 1);
    kyy.dateStr += "" + date.getDate();
    localStorageSetItem("kyy", kyy);
  });

  // 一键设置按钮
  $(".oneKeyBtn").click(async () => {

    let flag = $(".textarea").eq(0).val() ==
      "请替换拼多多一键打包的数据，采集页面才需要~~~";

    if (flag) {
      if (localStorageGetItem("kyyData") && localStorageGetItem("kyyData").globalGoodsCode) {
        initPddData();
      } else {
        console.log("请先粘贴拼多多数据...");
        return;
      }
    }

    if (isRunning) {
      console.log("isRunning...");
      return;
    }

    isRunning = true;


    // 没有汇率则先请求
    console.log("rate:", getTbRate());
    if (!getTbRate()) {
      await initRate();
    }

    await initCollect();

    isRunning = false;
  });

  // 一键折扣
  $(".goodsBtn").click(async () => {
    if (isRunning) {
      console.log("isRunning...");
      return;
    }

    isRunning = true;

    await oneKeyDiscount($("#discountInput").val());
    await wait(500);
    await translateLanguage();

    // 自动更新
    getHandleBySelectorAndText($(".v-btn__content"), "更新").click();

    isRunning = false;
  });

  // test
  $(".testBtn").click(async () => {
    if (isRunning) {
      console.log("isRunning...");
      return;
    }

    isRunning = true;

    await test();

    isRunning = false;
  });

  // 初始化汇率
  $(".initRateBtn").click(initRate);
}

async function initPddData() {
  await anchors("商品源");

  if (localStorageGetItem("kyyData")) {
    kyyData = localStorageGetItem("kyyData");

    // ******************获取pdd信息**************** // 
    let handle = $('#appRoot div[title="全球商品货号"]').next();
    var inputHandle =
      handle.find("textarea").length > 0
        ? handle.find("textarea")[0]
        : handle.find("input")[0];

    let globalGoodsCode = inputHandle.value;
    if (kyyData.globalGoodsCode == globalGoodsCode) {
      // kyyData.pddData;
      $(".textarea").val(JSON.stringify(kyyData.pddData));
    } else {
      // 不是对应的全球商品编码则跳转
      jumpToOriginGoods();
    }
  } else {
    // local没有存储则跳转
    jumpToOriginGoods();
  }
}

// 原商品链接跳转
function jumpToOriginGoods() {
  let handle = $('#appRoot div[title="原商品链接"]').next();
  let btn = handle.find("a:contains('remove_red_eye')");
  btn.trigger("click");
}

async function test() {

  let btn = $('#main .v-tabs__item:contains("台湾")')[0];
  btn.click();

  // 遍历锚点，处理懒加载
  await wait(2000);

  anchors("店铺和类目");
  await selectItem("Lily-house 🎀北歐家居館");
  await wait(2000);

  expressInfo();
}

async function initCollect() {

  // 判断站点
  switch ($("#siteSelect").val()) {
    case "台湾": {
      let btn = $('#main .v-tabs__item:contains("台湾")')[0];
      btn.click();

      // 遍历锚点，处理懒加载
      await anchors();
      await wait(2000);

      anchors("店铺和类目");
      await selectItem("Lily-house 🎀北歐家居館");

      break;
    }
    default: break;
  }

  await wait(2000);
  // 自动同步了类目~
  // await initShopCategory();

  // 选择客优云分类
  // 暂时没有了分类
  // await selectItem(pddData.firstClassify);

  anchors("基本信息");
  // 添加商品描述
  await addGoodsDesc();

  await wait(500);
  await oneKeyDiscount();

  await wait(500);
  await translateLanguage();

  await wait(500);
  await expressInfo();
}










